/*
 * @Author: fanjs
 * @Date: 2025-03-06 13:27:18
 * @Description: 登录模块
 */
import { RouterContext } from 'koa-router'
import { api, auth } from '@core/decorator'
import UserModel from '@app/model/user'
import { AuthRouterContext } from 'router'
import { generateToken } from '@core/util'

@api.controller('/v1/auth')
class AuthController {
  /**
   * 手机号注册
   * @param phone 手机号
   * @param password 密码
   * @param authCode 授权码
   */
  @api.post('/register')
  async register(ctx: RouterContext) {
    const { phone, password, authCode } = ctx.request.body as any;
    await UserModel.validateParams(phone, password, authCode);

    // 注册用户
    const user = await UserModel.registerByPhone(phone, password);
    const token = generateToken(user.id, user.scope, user.nickname, 60 * 60 * 24 * 3);
    throw new global.errs.Success({
      token,
      user: {
        id: user.id,
        nickname: user.nickname,
        phone: user.phone
      }
    });
  }

  /**
   * 手机号登录
   * @param phone 手机号
   * @param password 密码
   * @param remember 是否记住密码
   * @returns token和用户信息
   */
  @api.post('/login')
  async login(ctx: RouterContext) {
    // 7天免登陆
    const { phone, password, remember } = ctx.request.body as any;

    const user = await UserModel.validateParams(phone, password);

    // 生成token，默认有效期3天， remember = 7天
    const expire_days = remember ? 7 : 3;
    const token = generateToken(user.id, user.scope, user.nickname, 60 * 60 * 24 * expire_days);
    throw new global.errs.Success({
      token,
      user: {
        id: user.id,
        nickname: user.nickname,
        phone: user.phone
      }
    });
  }

  /**
   * 获取当前登录用户信息
   */
  @api.get('/user')
  @api.auth('UserScope')
  @auth.login_required
  async getUserInfo(ctx: AuthRouterContext) {
    const { uid } = ctx.auth;

    const user = await UserModel.findOne({
      where: { id: uid }
    });
    if (!user) throw new global.errs.APIException('用户不存在');

    throw new global.errs.Success(user.toJSON());
  }

  /**
   * 退出登录
   */
  @api.post('/logout')
  @api.auth('UserScope')
  @auth.login_required
  async logout() {
    throw new global.errs.Success(true);
  }
} 